package com.max.xihu.concurrent.day01;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * @Author: Max
 * @Date: 2020-07-24 07:52
 * @Description:
 */
public class CountTask extends RecursiveTask<Integer> {

    private static final int THRESHOLD = 2;

    private int start;

    private int end;

    public CountTask(int start, int end){
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {

        int sum = 0;

        boolean can = (end - start) <= THRESHOLD;

        if (can){
            for (int i = start; i<=end; i++){
                sum += i;
            }
        }else{
            int mid = (start + end) / 2;
            CountTask left = new CountTask(start,mid);
            CountTask right = new CountTask(mid+1,end);
            left.fork();
            right.fork();

            int leftRet = left.join();
            int rightRet = right.join();
            sum = leftRet + rightRet;
        }
        return sum;
    }

    public static void main(String[] args) throws Exception {
        ForkJoinPool pool = new ForkJoinPool();
        CountTask task = new CountTask(1,100);
        Future<Integer> result = pool.submit(task);
        System.out.println(result.get());
    }


}
